package com.zhihao.takeaway.common.elasticsearchStudy;

import com.alibaba.fastjson.JSON;
import com.zhihao.takeaway.entity.Dish;
import com.zhihao.takeaway.mapper.DishMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class ContentController {

    @Autowired
    private ContentService contentService;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @GetMapping("/parse/{keywords}")
    public Boolean parse(@PathVariable("keywords")  String keywords)throws Exception{
        Boolean aBoolean = contentService.parseContent(keywords);
        return aBoolean;
    }

    @GetMapping("/search/{keywords}/{pageNo}/{pageSize}")
    public List<Map<String,Object>> search(@PathVariable("keywords") String keywords,
                                            @PathVariable("pageNo") Integer pageNo,
                                            @PathVariable("pageSize") Integer pageSize)throws Exception{
        return contentService.searchPage(keywords,pageNo,pageSize);
    }
//    导入数据用的
//    @GetMapping("/parse/keep")
//    public Boolean parseContent() throws Exception {
//        List<Dish> formData = dishMapper.selectList(null);
////        把查询到的数据放入es中
//        BulkRequest bulkRequest = new BulkRequest();
//        bulkRequest.timeout("2m");
//        for(int i = 0 ; i < formData.size() ; i++){
//            System.out.println(JSON.toJSONString(formData.get(i)));
//            bulkRequest.add(
//                    new IndexRequest("dish_search")
//                            .source(JSON.toJSONString(formData.get(i)), XContentType.JSON));
//        }
//        BulkResponse bulkItemResponses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
//        return !bulkItemResponses.hasFailures();
//    }
}
